﻿using MongoDB.Driver;
using Sustainalytics.Entities;
using Sustainalytics.Entities.SustainableProducts;
using Sustainalytics.ScreeningTool.Service;
using Sustainalytics.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.SustainableProducts.Service
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //[AutoInvalidateCacheOutput]
    [RoutePrefix("api/v1/spframework/{symbol}/categories")]
    [LogControllerFilter(true, true, false)]
    public class SPFrameworkCategoriesController : ApiController, ISPFrameworkCategoriesController
    {
        private readonly IMongoCollection<TemplateCriteria> _templateCriteriaCollection;
        private readonly IMongoCollection<SustainableProductsFramework> _sustainableProductsFramework;

        public SPFrameworkCategoriesController(
            IMongoCollection<TemplateCriteria> templateCriteriaCollection,
            IMongoCollection<SustainableProductsFramework> sustainableProductsFramework)
        {
            _templateCriteriaCollection = templateCriteriaCollection;
            _sustainableProductsFramework = sustainableProductsFramework;
        }

        [Route("")]
        public HttpResponseMessage Get([FromUri] string symbol, bool includeAllFields = false)
        {
            try
            {
                var categories = _sustainableProductsFramework.Find(x => x.Symbol == symbol)
                    .Project(x => x.Categories)
                    .ToList()
                    .SelectMany(x => x);


                var finalCategories = new List<object>();
                foreach (var cat in categories)
                {
                    var templateId = _templateCriteriaCollection
                        .Find(x => x.CriteriaType == CriteriaTypeEnum.CriteriaType4 &&
                            x.CriteriaEntityField.Contains(cat.Symbol) &&
                            x.IsScreenable)
                        .Project(x => x.Id)
                        .FirstOrDefault();

                    int maxval = 0;
                    var lastSPRange = cat.RevenueRange.Values.OrderBy(rr => rr.RangeId).LastOrDefault(rr => rr.NA);
                    maxval = lastSPRange != null ? 5 - lastSPRange.RangeId : 5;
                    finalCategories.Add(new
                    {
                        cat.CategoryOfInvolvement,
                        RevenueRange = cat.RevenueRange.Values.ToList().ConvertAll<PIRangeDto>(rr => PIRangeDto.CreateComplete(rr)),
                        MaxValue = maxval,
                        CategorySymbol = cat.Symbol,
                        RevenueRangeYesNo = true,
                        TemplateCriteriaId = templateId
                    });
                }
                return Request.CreateResponse(HttpStatusCode.OK, finalCategories);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, new { ErrorCode = 1010 });
            }
        }
    }
}
